//
//  RootViewController.m
//  VMIX
//
//  Created by jeffs on 5/14/10.
//  Copyright VMIX Media Inc. 2010. All rights reserved.
//

#import "RootViewController.h"
#import "DetailViewController.h"
#import "CollectionsPopOver.h"
#import "VmixGridViewController.h"
// This framework was imported so we could use the kCFURLErrorNotConnectedToInternet error code.
#import <CFNetwork/CFNetwork.h>

/*
 This template does not ensure user interface consistency during editing operations in the table view. You must implement appropriate methods to provide the user experience you require.
 */

@interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end

@implementation RootViewController

@synthesize detailViewController, collectionsList, mediasList, oppQueue, getCollectionMediasOperation, getCollectionsOperation, video, collection, videoCell, authData, collectionsPopOver, collectionsPopOverView, collectionsButton;
@synthesize imageCache, rightArrowButton, leftArrowButton, gridViewController, appLaunched, viewContainsNoContent;


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
	self.appLaunched = NO;
    self.clearsSelectionOnViewWillAppear = NO;
    self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
	self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
	self.collectionsButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    self.collectionsButton.frame = CGRectMake(110.0, 360.0, 200.0, 30.0);
	[self.collectionsButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0]];
    [self.collectionsButton  setTitle:@"" forState:UIControlStateNormal];
    self.collectionsButton.backgroundColor = [UIColor clearColor];
    [self.collectionsButton  setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
    UIImage *buttonImageNormal = [UIImage imageNamed:@"alternate_blue_button.png"];
    //UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [self.collectionsButton  setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
	[self.collectionsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
    //UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
   // [playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
    [self.collectionsButton addTarget:self action:@selector(showCollections) forControlEvents:UIControlEventTouchUpInside];
	
	self.navigationItem.titleView = self.collectionsButton;
	
	UIImage *arrowImg = [UIImage imageNamed:@"right_arrow.png"];
	UIButton * arrowButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	arrowButton.frame = CGRectMake(0, 0, 21, 30);
	arrowButton.backgroundColor = [UIColor clearColor];
	[arrowButton setBackgroundImage:arrowImg forState:UIControlStateNormal];
	[arrowButton addTarget:self action:@selector(expandView) forControlEvents:UIControlEventTouchUpInside];
	self.rightArrowButton = [[UIBarButtonItem alloc] initWithCustomView:arrowButton];
	
	UIImage *arrowImg2 = [UIImage imageNamed:@"left_arrow.png"];
	UIButton * arrowButton2 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	arrowButton2.frame = CGRectMake(0, 0, 21, 30);
	arrowButton2.backgroundColor = [UIColor clearColor];
	[arrowButton2 setBackgroundImage:arrowImg2 forState:UIControlStateNormal];
	[arrowButton2 addTarget:self action:@selector(collapseView) forControlEvents:UIControlEventTouchUpInside];
	self.leftArrowButton = [[UIBarButtonItem alloc] initWithCustomView:arrowButton2];
	
	self.navigationItem.rightBarButtonItem = self.rightArrowButton ;
	
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_center_large_gray.png"]];
	self.tableView.backgroundColor = [UIColor clearColor];
	self.tableView.separatorColor = [UIColor grayColor];
    
	NSString *collectionAPI = [NSString stringWithFormat:@"%@action=getCollections&collection_id=%@&output=xml&atoken=%@", COLLECTION, CONTAINER_COLLECTION, ATOKEN ];
	NSURL *url = [NSURL URLWithString: collectionAPI];
	NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
	NSURLConnection *initialConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
	[initialConnection release];
	self.collectionsList = [[NSMutableArray alloc] init];
	self.mediasList = [[NSMutableArray alloc] init];
	self.imageCache = [[NSMutableDictionary alloc] init];
	
	
	
	/*
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	//Setup operation queue to spin up non blocking execution thread.
	self.oppQueue = [[NSOperationQueue alloc] init];
	self.getMediaListOperation = [[GetMediaListOperation alloc] init];
	NSString *mediaAPI = [NSString stringWithFormat:@"%@action=getMediaList&class_id=1&start=250&limit=10&output=xml&show_total_view=1", MEDIA];
	self.getMediaListOperation.mediaApi =  mediaAPI;
	self.getMediaListOperation.delegate = self;
	[oppQueue addOperation:self.getMediaListOperation];
	[self.getMediaListOperation release];
	 */
	
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
 */
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
 */
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
 */

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.    
    return YES;
}


- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    
   // NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
   // cell.textLabel.text = [[managedObject valueForKey:@"timeStamp"] description];
}

- (void)fetchImage:(NSArray *)args {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    UIImageView *iv = [args objectAtIndex:0];
    NSString *str = [args objectAtIndex:1];
    NSURL *imageUrl = [NSURL URLWithString:str];
    NSURLRequest *imageReq = [NSURLRequest requestWithURL:imageUrl];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *imageData = [NSURLConnection sendSynchronousRequest:imageReq returningResponse:&response error:&error];
    UIImage *theImage;
	if(imageData == nil){
		theImage = [UIImage imageNamed:@"mobilesdk-blankthumb1.png"];
	}else{
		theImage = [UIImage imageWithData:imageData];
	}
	[self.imageCache setObject:theImage forKey:str];
   // if (iv.tag == [[args objectAtIndex:2] intValue]) {
       [iv setImage:theImage];
   // }
    [pool release];
}

- (UIImage *)getImageForURL:(NSString *)str inImageView:(UIImageView *)iv {
    UIImage *i = nil;
    if ([self.imageCache objectForKey:str] != nil) {
        i = [self.imageCache objectForKey:str];
    } else {
        i = [[UIImage alloc] init];
        NSArray *args = [NSArray arrayWithObjects:iv, str, [NSNumber numberWithInt:iv.tag], nil];
        [self performSelectorInBackground:@selector(fetchImage:) withObject:args];

    }
    return i;
}


#pragma mark -
#pragma mark Table view data source

//JAS - Can ignore this for now since we only have 1 section in the table
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[fetchedResultsController sections] count];
	
}*/


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	int count = [self.mediasList count];
	// ff there's no data yet, return enough rows to fill the screen
    if (count == 0)
	{
        return 1;
    }
    return count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	static NSString *CellIdentifier = @"Cell";
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";
    
    // add a placeholder cell while waiting on table data
    int nodeCount = [self.mediasList count];
	
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

	    //cell.detailTextLabel.text = @"Loading…";
        if( self.viewContainsNoContent = FALSE ) {
            // add spinner animation if we're really loading data
            UIActivityIndicatorView *piespinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
            piespinner.hidden = NO;
            [piespinner startAnimating];
            piespinner.frame = CGRectMake(150.0, 40.0, 20, 20.0);
            [cell.contentView addSubview:piespinner];
        }
        else {
            // otherwise tell them nothing is here to see.
            cell.detailTextLabel.text = @"No Content Available.";
        }	

		return cell;
    }
    
	
	VideoCell *cell = (VideoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		NSLog(@"Loading cell from NIB");
		[[NSBundle mainBundle] loadNibNamed:@"VideoCell" owner:self options:nil];
		cell = videoCell;
	}else {
		// mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
    }
	
	if(self.video== nil){
		VmixVideo *v = [[VmixVideo alloc] init];
		self.video = v;
	}
    self.video = [self.mediasList objectAtIndex:indexPath.row];
	
	cell.titleLabel.text = self.video.title;
	cell.descriptionText.text = self.video.description;
	
	NSString *path = self.video.thumbnail;
	NSString *imgMan = [NSString stringWithFormat:@"http://cdn-aki.vmixcore.com/imgman.jpg?fill=000000000&url=%@&width=216&height=120", path];
	//NSData *data = [NSData dataWithContentsOfURL:url];
	//UIImage *img = [[UIImage alloc] initWithData:data];
	cell.videoImageView.tag = indexPath.row + 1000;
	cell.videoImageView.image = [self getImageForURL:imgMan inImageView:cell.videoImageView];
    return cell;
	
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	if ((indexPath.row % 2) != 0){
		cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.05];
	}
	
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return NO;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
		//JAS - NOT going to be deleting stuff from the rows for now - no persistent store.

    }   
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	//[self collapseView];
	VmixVideo *v = (VmixVideo *) [self.mediasList objectAtIndex:indexPath.row];
	[detailViewController loadVideo:v];
}

-(void) getMediaListForCollection:(VmixCollection *) theCollection{
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	//Setup operation queue to spin up non blocking execution thread.
	self.getCollectionMediasOperation = [[GetCollectionMediasOperation alloc] init];
	NSString *collectionMediasApi = [NSString stringWithFormat:@"%@action=getCollectionMedias&collection_id=%@&atoken=%@&output=xml", COLLECTION, theCollection.collection_id, ATOKEN];
	self.getCollectionMediasOperation.collectionMediasApi =  collectionMediasApi;
	self.getCollectionMediasOperation.delegate = self;
	[oppQueue addOperation:self.getCollectionMediasOperation];
	[self.getCollectionMediasOperation release];
}

//Delegate method to comply with GetCollectionsOperationDelegate
- (void)didFinishParsingCollections:(NSMutableArray *) collectionsArray{
	
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	self.collectionsList = collectionsArray;
	self.collectionsPopOverView = [[[CollectionsPopOver alloc] init] autorelease];
	self.collectionsPopOverView.wheelSource = self.collectionsList;
	self.collectionsPopOverView.rootDelegate = self;
	VmixCollection *vc = (VmixCollection *) [self.collectionsList objectAtIndex:0];
	[self.collectionsButton  setTitle:vc.name forState:UIControlStateNormal];
	self.gridViewController = [[VmixGridViewController alloc] init];
	self.gridViewController.collectionsList = self.collectionsList;
	self.gridViewController.collection = vc;
	NSLog(@"Completed getCollections");
	[self getMediaListForCollection:vc];
	
}

//Delegate method to comply with GetMediaListOperationDelegate
- (void)didFinishParsingCollectionMedias:(NSMutableArray *) mediaArray{
	

	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	self.gridViewController.mediasArray = self.mediasList = mediaArray;
	self.gridViewController.delegate = self;
	NSLog(@"Completed getMediaList");

    // check if the mediaArray is empty before performing any action here
    if( [mediaArray count] > 0 ) {
        [self performSelectorOnMainThread:@selector(reloadTheTableData) 
                               withObject:nil
                            waitUntilDone:YES];
    }
    else {
        // turn off the table view spinner
        self.viewContainsNoContent = TRUE;
    }  

}



-(void) reloadTheTableData{
	

	[self.tableView reloadData];

		if(!self.appLaunched){
			VmixVideo *v = (VmixVideo *) [self.mediasList objectAtIndex:0];
			[detailViewController loadVideo:v];
			self.appLaunched = YES;
		}
}


-(void) updateTableWithCollection:(VmixCollection *) theCollection{
	
	[self.collectionsButton  setTitle:theCollection.name forState:UIControlStateNormal];
	[self.collectionsPopOver dismissPopoverAnimated:YES];
	//self.imageCache = nil;
	self.mediasList = nil;
	self.gridViewController.collection = theCollection;
	[self.tableView reloadData];
	[self getMediaListForCollection:theCollection];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 100.5f;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.authData = [NSMutableData data];  
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.authData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	
    //[connection release];
    //[self.authData release];
	
	NSLog(@"The Connection did fail with error");
	if ([error code] == kCFURLErrorNotConnectedToInternet)
	{
		
		NSString *title = [NSString stringWithFormat:@"Network Connection Required"];
		NSString *alertMessage = @"This application requires an internet connection to function properly. Please connect to the internet and re-launch the application";
		NSString *ok = [NSString stringWithFormat:@"Ok"];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage  delegate:self cancelButtonTitle:ok otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	//Setup operation queue to spin up non blocking execution thread.
	self.oppQueue = [[NSOperationQueue alloc] init];
	self.getCollectionsOperation = [[GetCollectionsOperation alloc] init];
	NSString *collectionsAPI = [NSString stringWithFormat:@"%@action=getCollections&collection_id=%@&output=xml&atoken=%@", COLLECTION, CONTAINER_COLLECTION, ATOKEN ];
	self.getCollectionsOperation.collectionsApi =  collectionsAPI;
	self.getCollectionsOperation.delegate = self;
	[oppQueue addOperation:self.getCollectionsOperation];
	[self.getCollectionsOperation release];
	
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
	// show error right away, since the auth token should work
	NSLog(@"Authentication challenge received");
    /*if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:PARTNER_ID
                                                 password:PASSWORD
                                              persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
	 */
	[[challenge sender] cancelAuthenticationChallenge:challenge];
	NSString *title = [NSString stringWithFormat:@"Login Failed"];
	NSString *alertMessage = @"Username and/or Password not accepted";
	NSString *ok = [NSString stringWithFormat:@"Try Again"];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage  delegate:self cancelButtonTitle:ok otherButtonTitles:nil];
	[alert show];
	[alert release];
		
    //}
}



- (void)showCollections{
	/*
	if([[self.segmentControl titleForSegmentAtIndex: self.segmentControl.selectedSegmentIndex] isEqual:@"Existing User"])
	{
		self.createView.hidden = YES;
		self.existingView.hidden = NO;
	}else{
		self.createView.hidden = NO;
		self.existingView.hidden = YES;
	}*/
	NSLog(@"The value changed");
	
	self.collectionsPopOver = [[[UIPopoverController alloc] 
								initWithContentViewController:self.collectionsPopOverView] autorelease];               

[self.collectionsPopOver presentPopoverFromRect:self.collectionsButton.frame inView:self.navigationController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
	
}

-(void) expandView {
	
	[detailViewController expandView];
	self.navigationItem.rightBarButtonItem = self.leftArrowButton ;
}
- (void) collapseView {
	
	[detailViewController collapseView];
	self.navigationItem.rightBarButtonItem = self.rightArrowButton ;
	
	
}

- (void)insertNewObject:(id)sender
{
	// do nothing right now
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    
    [detailViewController release];
    
    [super dealloc];
}

@end
